package com.white.FalseWorld;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.white.FalseWorld.beans.personals;
import com.white.FalseWorld.fragment.FW_BottomFragement;
import com.white.FalseWorld.utils.GlideEngine;
import com.white.FalseWorld.utils.GlideRoundImage;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

import static java.sql.DriverManager.getConnection;

/**
 * 作者：white
 * 时间：2020/10/4.
 */
public class LoginStepActivity extends AppCompatActivity {

    private TextView step2_wxid;
    private EditText step2_username,step2_wxTable;
    private ImageView step2_headpicture,step2_backpicture;
    private LinearLayout step2_headpicture_layout,step2_username_layout,step2_wxid_layout,step2_wxTable_layout,
    step2_backpicture_layout;
    private Button step2_save;

    private String wx_id;

    //上传图片本地路径
    String localpicture_head,localpicture_head_name,localpicture_back,localpicture_back_name;
    String now_time;

    int head_change=0,back_change=0;

    private ArrayList<personals> list=new ArrayList<personals>(  );
    GlideRoundImage glideRoundImage=new GlideRoundImage();


    FW_BottomFragement fw_bottomFragement=new FW_BottomFragement();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_login_step );
        ImmersionBar.with(this).init();//一键透明状态栏
        wx_id = getIntent().getStringExtra("user");

        //判断权限是否已申请，未申请则进行申请
        if (ContextCompat.checkSelfPermission( LoginStepActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE )
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 120);
        }
        now_time= String.valueOf( System.currentTimeMillis() );
        //初始化，绑定组件
        step2_username=findViewById( R.id.step2_username );
        step2_wxid=findViewById( R.id.step2_wxid );
        step2_wxTable=findViewById( R.id.step2_wxTable );
        step2_headpicture=findViewById( R.id.step2_headpicture );
        step2_backpicture=findViewById( R.id.step2_backpicture );
        step2_headpicture_layout=findViewById( R.id.step2_headpicture_layout );
        step2_username_layout=findViewById( R.id.step2_username_layout );
        step2_wxid_layout=findViewById( R.id.step2_wxid_layout );
        step2_wxTable_layout=findViewById( R.id.step2_wxTable_layout );
        step2_backpicture_layout=findViewById( R.id.step2_backpicture_layout );
        step2_save=findViewById( R.id.step2_save );
        step2_save.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (head_change==1 & back_change==1){
                    sendImgae( new File( localpicture_head ) );
                    sendImgae(new File(localpicture_back));
                }else if (head_change==1 & back_change==0){
                    sendImgae(new File(localpicture_head));
                }else if (head_change==0 & back_change==1){
                    sendImgae(new File(localpicture_back));
                }

                wxLoginStep_insert_mysql();
                Toast.makeText( LoginStepActivity.this,"更改成功",Toast.LENGTH_SHORT ).show();
                Intent intent=new Intent( LoginStepActivity.this,IndexActivity.class );
                intent.putExtra( "user",wx_id );
                startActivity( intent );
            }
        } );
        step2_headpicture_layout.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select_Onepicture(1,0);
            }
        } );
        step2_backpicture_layout.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select_Onepicture(1,1);
            }
        } );
        replaceFragment_bottom( fw_bottomFragement );
        /**
         * 查询对应的信息填写在对应的组件上
         * 根据所提交的数据，与数据库进行对接
         */
        wxLoginStep_query_mysql_init();


    }
    private void select_Onepicture(int maxSelectpictureNum,int ResultCode) {
        //一张图片选择器
        PictureSelector.create( this )
                .openGallery( PictureMimeType.ofImage() )
                .loadImageEngine( GlideEngine.createGlideEngine())
                .isWeChatStyle(true)//开启R.style.picture_WeChat_style样式
                .maxSelectNum(maxSelectpictureNum)//最大选择数量
                .enableCrop(true)//是否开启裁剪
                .compress(true)//是否压缩
                .showCropFrame(true)// 是否显示裁剪矩形边框
                .withAspectRatio(1,1)//裁剪比例
                .previewImage(true)
                .previewEggs(true)//预览图片时是否增强左右滑动图片体验
                .forResult( ResultCode );
    }

    private void replaceFragment_bottom(FW_BottomFragement fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace( R.id.fw_bottomframe_login_step, fragment );
        fragmentTransaction.commit();

    }
    private void wxLoginStep_insert_mysql() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection cn= getConnection( getString( R.string.mysql_address_utf8 )+"?useUnicode=true&characterEncoding=UTF-8",getString( R.string.mysql_username ),getString( R.string.mysql_password ));

                    String temp_username= step2_username.getText().toString();
                    String temp_wxTable=step2_wxTable.getText().toString();
                    String sql="select";

                    System.out.println( "用户名："+temp_username+"     标签："+temp_wxTable );

                    /**
                     *
                     * 判断用户是否更改了头像或背景图，如果没有更新则不做改变，相反则改变
                     */
                    if (head_change==0 & back_change==0){
                        sql="UPDATE personals SET user='"+temp_username+"',wx_pyq_label='"+temp_wxTable+"' WHERE user_wx='"+wx_id+"'";
                    }else if (head_change==1 & back_change==0){
                        sql="UPDATE personals SET user='"+temp_username+"',headpicture='"+localpicture_head_name+"',wx_pyq_label='"+temp_wxTable+"' WHERE user_wx='"+wx_id+"'";
                    }else if (head_change==1 & back_change==1){
                        sql="UPDATE personals SET user='"+temp_username+"',headpicture='"+localpicture_head_name+"',wx_pyq_label='"+temp_wxTable+"',wx_pyq_picture='"+localpicture_back_name+"' WHERE user_wx='"+wx_id+"'";
                    }else if (head_change==0 & back_change==1){
                        sql="UPDATE personals SET user='"+temp_username+"',wx_pyq_label='"+temp_wxTable+"',wx_pyq_picture='"+localpicture_back_name+"' WHERE user_wx='"+wx_id+"'";
                    }
                    Statement st=(Statement)cn.createStatement();
                    if (st.executeUpdate( sql )==0){
                        Toast.makeText( getApplicationContext(),getString( R.string.error ),Toast.LENGTH_LONG ).show();
                    }
                    cn.close();
                    st.close();
                    System.out.println("更新数据库操作执行完毕");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode){
            case 0:
                // 结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult( data );
                localpicture_head=selectList.get( 0 ).getCompressPath();
                int img_path_length=selectList.get( 0 ).getCompressPath().split( "/" ).length;
                localpicture_head_name=selectList.get( 0 ).getCompressPath().split( "/" )[img_path_length-1];
                step2_headpicture.setImageURI( Uri.fromFile( new File(selectList.get( 0 ).getCompressPath()) ) );
                head_change=1;
                break;
            case 1:
                // 结果回调
                List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult( data );
                localpicture_back=selectList1.get( 0 ).getCompressPath();
                int img_path_length1=selectList1.get( 0 ).getCompressPath().split( "/" ).length;
                localpicture_back_name=selectList1.get( 0 ).getCompressPath().split( "/" )[img_path_length1-1];
                step2_backpicture.setImageURI( Uri.fromFile( new File(selectList1.get( 0 ).getCompressPath()) ) );
                back_change=1;
                break;
        }


    }

    /**
     *
     * 因各种原因，在此不设服务端来处理文件，而是通过ftp文件上传的形式来实现图片上传服务器
     * 后续在CSDN本人的博客(white_mvlog)中会写一遍Android端与服务器端是怎么进行数据交互（图片上传等）的
     *
     * @param localpicture
     */
    private void sendImgae(File localpicture) {
        new Thread( new Runnable() {
            @Override
            public void run() {
                FTPClient ftpClinet=new FTPClient();
                try {
                    /**
                     *
                     * 上传头像和朋友圈背景图片
                     */
                    ftpClinet.connect( getString( R.string.ftp_address ) );
                    ftpClinet.login( getString( R.string.ftp_username ),getString( R.string.ftp_password ) );
                    File file=new File( String.valueOf( localpicture ) );
                    // 设置中文编码集，防止中文乱码
                    ftpClinet.changeDirectory( getString( R.string.ftp_path ) );
                    ftpClinet.append( file );
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (FTPIllegalReplyException e) {
                    e.printStackTrace();
                } catch (FTPException e) {
                    e.printStackTrace();
                } catch (FTPAbortedException e) {
                    e.printStackTrace();
                } catch (FTPDataTransferException e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }


    private void wxLoginStep_query_mysql_init() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection cn= getConnection( getString( R.string.mysql_address ),getString( R.string.mysql_username ),getString( R.string.mysql_password ));
                    System.out.println("连接数据库成功");
                    String sql="SELECT * FROM personals WHERE user_wx='"+wx_id+"'";
                    Statement st=(Statement)cn.createStatement();
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        String temp_user=rs.getString("user");
                        String temp_headpicture=rs.getString( "headpicture" );
                        String temp_user_wx=rs.getString( "user_wx" );
                        String temp_wx_pyq_label=rs.getString( "wx_pyq_label" );
                        String temp_wx_pyq_picture=rs.getString( "wx_pyq_picture" );
                        personals personals=new personals();
                        personals.setUser( temp_user );
                        personals.setHeadpicture( temp_headpicture );
                        personals.setUser_wx( temp_user_wx );
                        personals.setWx_pyq_label( temp_wx_pyq_label );
                        personals.setWx_pyq_picture( temp_wx_pyq_picture );
                        list.add(personals);
                    }
                    cn.close();
                    st.close();
                    rs.close();
                    Message msg = new Message();
                    Bundle data = new Bundle();

                    //将获取到的list装载到msg中
                    ArrayList temp_list=new ArrayList(  );
                    temp_list.add( list );
                    data.putParcelableArrayList( "list",temp_list );
                    msg.setData(data);
                    msg.what = 1;
                    //发消息到主线程
                    handler.sendMessage(msg);

                    System.out.println("连接数据库操作执行完毕");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }
    //因为mysql在新线程中运行，所以得重新回到UI线程进行组件内容的修改等操作
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

                Bundle data = msg.getData();
                ArrayList<personals> temp_hand_list=new ArrayList<personals>(  );

                ArrayList list = data.getParcelableArrayList("list");
                temp_hand_list= (ArrayList<personals>) list.get(0);//强转成你自己定义的list，这样list2就是你传过来的那个list了。

                //设置UI
                if (!String.valueOf( temp_hand_list.get( 0 ).getHeadpicture() ).equals( "" )|
                !String.valueOf( temp_hand_list.get( 0 ).getHeadpicture() ).equals( " " )|
                !String.valueOf( temp_hand_list.get( 0 ).getHeadpicture() ).equals( "null" )){
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(getString( R.string.url_prefix )+String.valueOf( temp_hand_list.get( 0 ).getHeadpicture() ))
                            .apply( glideRoundImage.getoptions() )
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                    Drawable drawable = new BitmapDrawable(resource);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                        step2_headpicture.setImageDrawable(drawable);
                                    }
                                }

                            });
                }
                if (!String.valueOf( temp_hand_list.get( 0 ).getWx_pyq_picture() ).equals( "" )|
                        !String.valueOf( temp_hand_list.get( 0 ).getWx_pyq_picture() ).equals( " " )|
                        !String.valueOf( temp_hand_list.get( 0 ).getWx_pyq_picture() ).equals( "null" )){
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(getString( R.string.url_prefix )+String.valueOf( temp_hand_list.get( 0 ).getWx_pyq_picture() ))
                            .apply( glideRoundImage.getoptions() )
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                    Drawable drawable = new BitmapDrawable(resource);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                        step2_backpicture.setImageDrawable(drawable);
                                    }
                                }

                            });
                }

                step2_username.setText( String.valueOf( temp_hand_list.get( 0 ).getUser() ) );
                step2_wxid.setText( String.valueOf( temp_hand_list.get( 0 ).getUser_wx() ) );
                step2_wxTable.setText( String.valueOf( temp_hand_list.get( 0 ).getWx_pyq_label() ) );
            } else if (msg.what ==0) {
                Toast.makeText(getApplicationContext(),"请求资源不成功",Toast.LENGTH_LONG).show();
            }
        }
    };



}
